package edu.tgc.service.qrtz;

import org.quartz.ScheduleBuilder;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.SimpleTrigger;
import org.quartz.Trigger;

import edu.tgc.entity.qrtz.QrtzTrigger;

public class SimpleTriggerScheduleBuilder implements TriggerScheduleBuilder {

    @Override
    public ScheduleBuilder<SimpleTrigger> build(QrtzTrigger qrtzTrigger) {
        SimpleScheduleBuilder triggerBuilder = SimpleScheduleBuilder.simpleSchedule();
        if (qrtzTrigger.getRepeatCount() != null) { // 重复次数
            triggerBuilder.withRepeatCount(qrtzTrigger.getRepeatCount());
        } else {
            triggerBuilder.withRepeatCount(SimpleTrigger.REPEAT_INDEFINITELY);
        }
        triggerBuilder.withIntervalInMilliseconds(qrtzTrigger.getIntervalInMilliseconds()); // 重复时间
        // 设置触发机制 默认 SimpleTrigger.MISFIRE_INSTRUCTION_SMART_POLICY
        if (SimpleTrigger.MISFIRE_INSTRUCTION_FIRE_NOW == qrtzTrigger.getMisfireInstruction().intValue()) {
            triggerBuilder.withMisfireHandlingInstructionFireNow();
        } else if (SimpleTrigger.MISFIRE_INSTRUCTION_RESCHEDULE_NEXT_WITH_EXISTING_COUNT == qrtzTrigger.getMisfireInstruction().intValue()) {
            triggerBuilder.withMisfireHandlingInstructionNextWithExistingCount();
        } else if (SimpleTrigger.MISFIRE_INSTRUCTION_RESCHEDULE_NEXT_WITH_REMAINING_COUNT == qrtzTrigger.getMisfireInstruction().intValue()) {
            triggerBuilder.withMisfireHandlingInstructionNextWithRemainingCount();
        } else if (SimpleTrigger.MISFIRE_INSTRUCTION_RESCHEDULE_NOW_WITH_EXISTING_REPEAT_COUNT == qrtzTrigger.getMisfireInstruction().intValue()) {
            triggerBuilder.withMisfireHandlingInstructionNowWithExistingCount();
        } else if (SimpleTrigger.MISFIRE_INSTRUCTION_RESCHEDULE_NOW_WITH_REMAINING_REPEAT_COUNT == qrtzTrigger.getMisfireInstruction().intValue()) {
            triggerBuilder.withMisfireHandlingInstructionNowWithRemainingCount();
        } else if (Trigger.MISFIRE_INSTRUCTION_IGNORE_MISFIRE_POLICY == qrtzTrigger.getMisfireInstruction().intValue()) {
            triggerBuilder.withMisfireHandlingInstructionIgnoreMisfires();
        }
        return triggerBuilder;
    }
}
